package com.leetcode.partition5;

import java.util.HashMap;
import java.util.Map;

/**
 * @author `RKC`
 * @date 2021/9/9 12:45
 */
public class LC454四数相加2 {

    public static int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        return hashtable(nums1, nums2, nums3, nums4);
    }

    public static void main(String[] args) {
        int[] nums1 = {1, 2}, nums2 = {-2, -1}, nums3 = {-1, 2}, nums4 = {0, 2};
        System.out.println(fourSumCount(nums1, nums2, nums3, nums4));
    }

    private static int hashtable(final int[] nums1, final int[] nums2, final int[] nums3, final int[] nums4) {
        Map<Integer, Integer> ht = new HashMap<>();         //key为nums1[i]+nums2[j]，value为出现的次数
        for (int i = 0; i < nums1.length; i++) {
            for (int j = 0; j < nums2.length; j++) {
                int sum = nums1[i] + nums2[j];
                if (ht.containsKey(sum)) ht.put(sum, ht.get(sum) + 1);
                else ht.put(sum, 1);
            }
        }
        int answer = 0;
        for (int i = 0; i < nums3.length; i++) {
            for (int j = 0; j < nums4.length; j++) {
                int key = -(nums3[i] + nums4[j]);
                if (ht.containsKey(key)) {
                    answer += ht.get(key);
                }
            }
        }
        return answer;
    }
}
